package com.hs.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.hs.entity.RestBean;
import com.hs.entity.dto.Order;
import com.hs.service.OrderService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/pay")
public class PayController {

    @Resource
    private OrderService orderService;
    // 支付宝支付配置
    //支付宝应用的唯一标识
    private static final String APP_ID = "9021000142666595";
    //商户的私钥
    private static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9B4Mz1+/U6hclXHkqjDTaoyah/jcD5LrMObMDoYQ0/ZjGC0Xw7R0acc4laCa3l4fmHB/c6tLDnh/veOQwHFBro3moPpYux3dj8//PqXFh3+Bu5H7eUiGXlQhUrllv+ClmIjVSEDAhPckKFYjXJxaUInx3wJzvXAgLA8IvEusOsTYcNmJ2VmP7/cN8NUyuESt8krYHS7lTDJgO6vS44fRw+Q/SsGTQmeAn1xpnhLygWMR5GJh3Iph4mAaz+Qg9f0Q9H80lHPnPYvG+AX/+wUptTnxj8cpcOSDnU1JRkmc5zluAASY1LzGemDbW9vlTHPN4EutWKRdtNejuMKYBaRqLAgMBAAECggEAcw+jmWcToXJsbF2Bk5iMg5lT5r8rFb+gxLdKdCdYpjjHSaWLCUALuxES/koLZy1hl3v/GSYG7PPPVKEtpOtXOG3lm7edCxR3Y+weBnWJgp4XquiDISi1MeORkpod7r4L1RN1iWI5KcLGINFC3lP4tmrXgL1JyZknfCzpgmXtlp7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Y_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu6qzHI/3sWbpQS2WNMP7lCRTxRmiZD3yihBOkYxPqckauamx6oSPKtFHpjkD4v2kqejog7DeedSpdKhnnIzvQ9QZv8bHItXjAkvjXhF3wWRBBKLuEN1iIECjMMU9r8JN2R2MuO8XILNnkF4/sAhu6vskAYOZ8KwrJFlvabwU6tunqLfeNAgxUG+RdDfKEZU8ciTCe5S0SFrw8qu20i3Zq9+x3Q4VBlzzEWZSR2cCGlakaPGTXafRwNB47C5zLnF12LlvgFDt5RpT6NS7Fzbr4Thi+y7bio+PoJ0rXwb/e68d3OIoYwek9Ucec7MdOgnPb0JpVDsMBSrgXRqU2t3osQIDAQAB";
    //付宝异步通知商户的地址
    private static final String NOTIFY_URL = "http://localhost/api/pay/notify";
    //支付完成后跳转的前端页面地址
    private static final String RETURN_URL = "http://localhost:5173/user/pay/success";
    //支付宝网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    @PostMapping("/create")
    public String createPayment(@RequestBody Order order) {
        try {
            // 直接使用前端传来的 user_id，不需要再次获取
            if (order.getUser_id() == null) {
                return null;
            }

            // 生成随机订单号
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
            Integer orderId = Math.abs(uuid.hashCode()); // 取绝对值，避免负数

            order.setId(orderId);

            // 设置订单其他基本信息
            order.setOrder_type(1); // 设置订单类型
            order.setStatus(0);     // 设置订单状态为未支付

            // 保存订单到数据库
            orderService.save(order);

            // 创建支付宝订单
            AlipayClient alipayClient = new DefaultAlipayClient(
                    GATEWAY_URL,
                    APP_ID,
                    PRIVATE_KEY,
                    "json",
                    "UTF-8",
                    ALIPAY_PUBLIC_KEY,
                    "RSA2"
            );

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(NOTIFY_URL);
            request.setReturnUrl(RETURN_URL);

            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", order.getId().toString()); // 使用数据库生成的订单ID
            bizContent.put("total_amount", order.getMoney());
            bizContent.put("subject", "搬家服务订单-" + order.getId());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            request.setBizContent(bizContent.toString());

            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                return response.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 支付宝异步通知接口
    @PostMapping("/notify")
    public String notifyPayment(HttpServletRequest request) {
        try {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, requestParams.get(name)[0]);
            }

            if(AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "UTF-8", "RSA2")) {
                String orderId = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");

                if("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 更新订单状态
                    Order order = orderService.getById(orderId);
                    if(order != null) {
                        order.setStatus(1); // 设置为已支付
                        orderService.updateById(order);
                    }
                    return "success";
                }
            }
            return "failure";
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }
}
